3 * Backend for uploading files from chunks.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
25 * Implements uploading from chunks
28 * @author Michael Dale
30 class UploadFromChunks
extends UploadFromFile
{
33 /** @var UploadStash */
39 protected $mChunkIndex;
41 protected $mVirtualTempPath;
43 /** @noinspection PhpMissingParentConstructorInspection */
46 * Setup local pointers to stash, repo and user (similar to UploadFromStash)
49 * @param UploadStash|bool $stash Default: false
50 * @param FileRepo|bool $repo Default: false
52 public function __construct( User
$user, $stash = false, $repo = false ) {
58 $this->repo
= RepoGroup
::singleton()->getLocalRepo();
62 $this->stash
= $stash;
64 wfDebug( __METHOD__
. " creating new UploadFromChunks instance for " . $user->getId() . "\n" );
65 $this->stash
= new UploadStash( $this->repo
, $this->user
);
72 public function tryStashFile( User
$user, $isPartial = false ) {
75 } catch ( UploadChunkVerificationException
$e ) {
76 return Status
::newFatal( $e->msg
);
79 return parent
::tryStashFile( $user, $isPartial );
84 * @throws UploadChunkVerificationException
85 * @deprecated since 1.28 Use tryStashFile() instead
87 public function stashFile( User
$user = null ) {
88 wfDeprecated( __METHOD__
, '1.28' );
91 return parent
::stashFile( $user );
95 * Calls the parent doStashFile and updates the uploadsession table to handle "chunks"
97 * @param User|null $user
98 * @return UploadStashFile Stashed file
100 protected function doStashFile( User
$user = null ) {
101 // Stash file is the called on creating a new chunk session:
102 $this->mChunkIndex
= 0;
105 // Create a local stash target
106 $this->mStashFile
= parent
::doStashFile( $user );
107 // Update the initial file offset (based on file size)
108 $this->mOffset
= $this->mStashFile
->getSize();
109 $this->mFileKey
= $this->mStashFile
->getFileKey();
111 // Output a copy of this first to chunk 0 location:
112 $this->outputChunk( $this->mStashFile
->getPath() );
114 // Update db table to reflect initial "chunk" state
115 $this->updateChunkStatus();
117 return $this->mStashFile
;
121 * Continue chunk uploading
123 * @param string $name
125 * @param WebRequestUpload $webRequestUpload
127 public function continueChunks( $name, $key, $webRequestUpload ) {
128 $this->mFileKey
= $key;
129 $this->mUpload
= $webRequestUpload;
130 // Get the chunk status form the db:
131 $this->getChunkStatus();
133 $metadata = $this->stash
->getMetadata( $key );
134 $this->initializePathInfo( $name,
135 $this->getRealPath( $metadata['us_path'] ),
136 $metadata['us_size'],
142 * Append the final chunk and ready file for parent::performUpload()
145 public function concatenateChunks() {
146 $chunkIndex = $this->getChunkIndex();
147 wfDebug( __METHOD__
. " concatenate {$this->mChunkIndex} chunks:" .
148 $this->getOffset() . ' inx:' . $chunkIndex . "\n" );
150 // Concatenate all the chunks to mVirtualTempPath
152 // The first chunk is stored at the mVirtualTempPath path so we start on "chunk 1"
153 for ( $i = 0; $i <= $chunkIndex; $i++
) {
154 $fileList[] = $this->getVirtualChunkLocation( $i );
157 // Get the file extension from the last chunk
158 $ext = FileBackend
::extensionFromPath( $this->mVirtualTempPath
);
159 // Get a 0-byte temp file to perform the concatenation at
160 $tmpFile = TempFSFile
::factory( 'chunkedupload_', $ext, wfTempDir() );
161 $tmpPath = false; // fail in concatenate()
163 // keep alive with $this
164 $tmpPath = $tmpFile->bind( $this )->getPath();
167 // Concatenate the chunks at the temp file
168 $tStart = microtime( true );
169 $status = $this->repo
->concatenate( $fileList, $tmpPath, FileRepo
::DELETE_SOURCE
);
170 $tAmount = microtime( true ) - $tStart;
171 if ( !$status->isOK() ) {
175 wfDebugLog( 'fileconcatenate', "Combined $i chunks in $tAmount seconds." );
177 // File system path of the actual full temp file
178 $this->setTempFile( $tmpPath );
180 $ret = $this->verifyUpload();
181 if ( $ret['status'] !== UploadBase
::OK
) {
182 wfDebugLog( 'fileconcatenate', "Verification failed for chunked upload" );
183 $status->fatal( $this->getVerificationErrorCode( $ret['status'] ) );
188 // Update the mTempPath and mStashFile
189 // (for FileUpload or normal Stash to take over)
190 $tStart = microtime( true );
191 // This is a re-implementation of UploadBase::tryStashFile(), we can't call it because we
192 // override doStashFile() with completely different functionality in this class...
193 $error = $this->runUploadStashFileHook( $this->user
);
195 $status->fatal( ...$error );
199 $this->mStashFile
= parent
::doStashFile( $this->user
);
200 } catch ( UploadStashException
$e ) {
201 $status->fatal( 'uploadstash-exception', get_class( $e ), $e->getMessage() );
205 $tAmount = microtime( true ) - $tStart;
206 $this->mStashFile
->setLocalReference( $tmpFile ); // reuse (e.g. for getImageInfo())
207 wfDebugLog( 'fileconcatenate', "Stashed combined file ($i chunks) in $tAmount seconds." );
213 * Returns the virtual chunk location:
217 function getVirtualChunkLocation( $index ) {
218 return $this->repo
->getVirtualUrl( 'temp' ) .
220 $this->repo
->getHashPath(
221 $this->getChunkFileKey( $index )
223 $this->getChunkFileKey( $index );
227 * Add a chunk to the temporary directory
229 * @param string $chunkPath Path to temporary chunk file
230 * @param int $chunkSize Size of the current chunk
231 * @param int $offset Offset of current chunk ( mutch match database chunk offset )
234 public function addChunk( $chunkPath, $chunkSize, $offset ) {
235 // Get the offset before we add the chunk to the file system
236 $preAppendOffset = $this->getOffset();
238 if ( $preAppendOffset +
$chunkSize > $this->getMaxUploadSize() ) {
239 $status = Status
::newFatal( 'file-too-large' );
241 // Make sure the client is uploading the correct chunk with a matching offset.
242 if ( $preAppendOffset == $offset ) {
243 // Update local chunk index for the current chunk
244 $this->mChunkIndex++
;
246 # For some reason mTempPath is set to first part
247 $oldTemp = $this->mTempPath
;
248 $this->mTempPath
= $chunkPath;
249 $this->verifyChunk();
250 $this->mTempPath
= $oldTemp;
251 } catch ( UploadChunkVerificationException
$e ) {
252 return Status
::newFatal( $e->msg
);
254 $status = $this->outputChunk( $chunkPath );
255 if ( $status->isGood() ) {
256 // Update local offset:
257 $this->mOffset
= $preAppendOffset +
$chunkSize;
258 // Update chunk table status db
259 $this->updateChunkStatus();
262 $status = Status
::newFatal( 'invalid-chunk-offset' );
270 * Update the chunk db table with the current status:
272 private function updateChunkStatus() {
273 wfDebug( __METHOD__
. " update chunk status for {$this->mFileKey} offset:" .
274 $this->getOffset() . ' inx:' . $this->getChunkIndex() . "\n" );
276 $dbw = $this->repo
->getMasterDB();
280 'us_status' => 'chunks',
281 'us_chunk_inx' => $this->getChunkIndex(),
282 'us_size' => $this->getOffset()
284 [ 'us_key' => $this->mFileKey
],
290 * Get the chunk db state and populate update relevant local values
292 private function getChunkStatus() {
293 // get Master db to avoid race conditions.
294 // Otherwise, if chunk upload time < replag there will be spurious errors
295 $dbw = $this->repo
->getMasterDB();
296 $row = $dbw->selectRow(
303 [ 'us_key' => $this->mFileKey
],
308 $this->mChunkIndex
= $row->us_chunk_inx
;
309 $this->mOffset
= $row->us_size
;
310 $this->mVirtualTempPath
= $row->us_path
;
315 * Get the current Chunk index
316 * @return int Index of the current chunk
318 private function getChunkIndex() {
319 if ( $this->mChunkIndex
!== null ) {
320 return $this->mChunkIndex
;
327 * Get the offset at which the next uploaded chunk will be appended to
328 * @return int Current byte offset of the chunk file set
330 public function getOffset() {
331 if ( $this->mOffset
!== null ) {
332 return $this->mOffset
;
339 * Output the chunk to disk
341 * @param string $chunkPath
342 * @throws UploadChunkFileException
345 private function outputChunk( $chunkPath ) {
346 // Key is fileKey + chunk index
347 $fileKey = $this->getChunkFileKey();
349 // Store the chunk per its indexed fileKey:
350 $hashPath = $this->repo
->getHashPath( $fileKey );
351 $storeStatus = $this->repo
->quickImport( $chunkPath,
352 $this->repo
->getZonePath( 'temp' ) . "/{$hashPath}{$fileKey}" );
354 // Check for error in stashing the chunk:
355 if ( !$storeStatus->isOK() ) {
356 $error = $storeStatus->getErrorsArray();
357 $error = reset( $error );
358 if ( !count( $error ) ) {
359 $error = $storeStatus->getWarningsArray();
360 $error = reset( $error );
361 if ( !count( $error ) ) {
362 $error = [ 'unknown', 'no error recorded' ];
365 throw new UploadChunkFileException( "Error storing file in '$chunkPath': " .
366 implode( '; ', $error ) );
372 private function getChunkFileKey( $index = null ) {
373 if ( $index === null ) {
374 $index = $this->getChunkIndex();
377 return $this->mFileKey
. '.' . $index;
381 * Verify that the chunk isn't really an evil html file
383 * @throws UploadChunkVerificationException
385 private function verifyChunk() {
386 // Rest mDesiredDestName here so we verify the name as if it were mFileKey
387 $oldDesiredDestName = $this->mDesiredDestName
;
388 $this->mDesiredDestName
= $this->mFileKey
;
389 $this->mTitle
= false;
390 $res = $this->verifyPartialFile();
391 $this->mDesiredDestName
= $oldDesiredDestName;
392 $this->mTitle
= false;
393 if ( is_array( $res ) ) {
394 throw new UploadChunkVerificationException( $res );